using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using ICSharpCode.SharpZipLib.GZip;

namespace DailyTestConsole
{
    public class LoginXiaoI
    {
        public LoginXiaoI(string strJcaptcha)
        {

            GetJSessionId();
            Login(strJcaptcha);
        }

        string strJcaptchaUrl = "http://wan.xiaoi.com/gucenter/JcaptchaServlet?for=login";
        string strBeforeLoginUrl = "http://wan.xiaoi.com/gucenter/war_frame_login.jsp";
        string strLoginUrl = "http://wan.xiaoi.com/gucenter/user!login.do";
        string strAfterLoginUrl = "http://wan.xiaoi.com/gucenter/war_frame_login.jsp";
        string strUserName = "vinsonking.jin@morningstar.com";
        string strPwd = "620@ms.com";

        string strJSessionIdInCookie = string.Empty;

        private void GetJSessionId()
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strBeforeLoginUrl);
            req.Accept = "*/*";
            req.Headers.Add("Accept-Language", "en-us");
            req.Headers.Add("Accept-Encoding", "gzip, deflate");
            req.Headers.Add("User-Agent", "Mozilla/4.0");
            req.Method = "GET";
            req.AllowAutoRedirect = false;
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)req.GetResponse();
            }
            catch(System.Exception ex)
            {
                string s = ex.Message;
            }

            if (response != null)
            {
                strJSessionIdInCookie = response.Headers.Get("Set-Cookie");
            }
            response.Close();
        }

        private void Login( string strJcaptcha )
        {
            string strPostData = "user.frameLogin=1&user.gameId=5&user.username={0}&user.password={1}&user.jcaptcha={2}&x=22&y=16";
            strPostData = string.Format(strPostData, strUserName, strPwd, strJcaptcha);

            byte[] postData = Encoding.ASCII.GetBytes(strPostData);

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strLoginUrl);
            req.Accept = "*/*";
            req.Headers.Add("Accept-Encoding", "gzip, deflate");
            req.ContentLength = postData.Length;
            req.ContentType = "application/x-www-form-urlencoded";
            req.Referer = "http://wan.xiaoi.com/gucenter/war_frame_login.jsp";
            req.AllowAutoRedirect = false;
            req.CookieContainer = new CookieContainer();

            HttpWebResponse response = (HttpWebResponse)req.GetResponse();

            int iCookieCount = response.Cookies.Count;
        }
    }
}
